import NNode from "./nnode.js";

export default class Snake{
    constructor(opt = {}){
        this.direction = opt.direction || 0;
        this.body = [];
        this.nodeSpace = 20;
        this.currentIndex = 994;
        this.moveSpeed = opt.speed || 50;
        this.body[0] = new NNode({
            x:300,y:100,z:999
        });
        this.body[1] = new NNode({
            x:280,y:100,z:998
        });
        this.body[2] = new NNode({
            x:260,y:100,z:997
        });
        this.body[3] = new NNode({
            x:240,y:100,z:996
        });
        this.body[4] = new NNode({
            x:220,y:100,z:995
        });
    }
    render(parent){
        for (let i = 0; i < this.body.length; i++) {
            parent.appendChild(this.body[i].element);
        }
    }
    move(tick){
        let step = this.moveSpeed / tick;
        // 头部移动
        let head = this.body[0];
        if(this.direction == 0 || this.direction == 360){
            head.centre.x += step;
        }else if (this.direction == 180){
            head.centre.x -= step;
        }else if(this.direction == 90){
            head.centre.y -= step;
        }else if(this.direction == 270){
            head.centre.y += step;
        }else if(this.direction > 0 && this.direction < 90){

        }else if(this.direction > 90 && this.direction < 180){

        }else if(this.direction > 180 && this.direction < 270){

        }else if(this.direction > 270 && this.direction < 360){
            
        }
        head.move();
        // 身体移动
        for (let i = this.body.length - 1; i > 0; i--) {
            let current = this.body[i];
            let prev = this.body[i-1];
            let tempX = prev.centre.x - current.centre.x;
            let tempY = prev.centre.y - current.centre.y;            
            let rate = Math.pow( Math.pow(tempX,2)+Math.pow(tempY,2) ,1/2) / step;            
            current.centre.x += tempX / rate;
            current.centre.y += tempY / rate;
            current.move();
        }
    }
}